const app = getApp()
let reqJs = require('../../utils/req.js')
let num = 0
let lineW = 33.3

Page({
    data: {
        id: '',
        reqData: "",
        index: 0,
        line_width: 33.3,
        projectList: '',
        answerList: '',
        isMutil: false,
        isOptionLocked: false,
        MutilNum: true,
        popupShow: false,
        type: '',
        popupData: '',
        isSuo: true,

        // 新增字段
        showCorrectHint: false, // 控制正确提示显示
        timer: null, // 自动跳转计时器

        // 错题相关
        isError: false,
        errorMsg: '',
    },

    onLoad(options) {
        if (options.id) {
            this.setData({
                id: options.id
            })
        } else {
            wx.showToast({
                title: '网络服务出错，请重新进入小程序',
                icon: 'none',
                duration: 2000
            })
        }
    },

    // 获取答题数据
    getAnswerList() {
        let res = {
            "code": 200,
            "message": "",
            "data": [{
                "id": "",
                "interlocution": [
                    {
                        "id": "q1",
                        "type": 0, // 全部改为单选题
                        "title": "红旗H5 PHEV电池的\"六面体堡垒绝缘防护\"达到国标多少倍？",
                        "subtext": "24倍国标要求的六面体堡垒绝缘防护技术，多维可靠密封技术20小时浸水不失效，240倍国标安全，涉水、洪涝极端情况安全防护云端电池医生24小时监测在线。买混动到红旗",
                        "items": [
                            {
                                "id": "q1_a",
                                "content": "A. 8倍",
                                "is_answer": 0,
                                "isChange": -1
                            },
                            {
                                "id": "q1_b",
                                "content": "B. 12倍",
                                "is_answer": 0,
                                "isChange": -1
                            },
                            {
                                "id": "q1_c",
                                "content": "C. 24倍",
                                "is_answer": 1,
                                "isChange": -1
                            }
                        ],
                        "correctItem": false
                    },
                    {
                        "id": "q2",
                        "type": 0, // 改为单选题
                        "title": "红旗H5 PHEV的混动系统拥有几种驱动模式？",
                        "subtext": "1.5T混动专用发动机 ，荣获\"中国心\"2024年度十佳发动机及混动系统，混动/纯电/燃油/增程四种模式，可油可电，出行随心。买混动到红旗",
                        "items": [
                            {
                                "id": "q2_a",
                                "content": "A. 2种（纯电/燃油）",
                                "is_answer": 0,
                                "isChange": -1
                            },
                            {
                                "id": "q2_b",
                                "content": "B. 3种（纯电/混动/燃油）",
                                "is_answer": 0,
                                "isChange": -1
                            },
                            {
                                "id": "q2_c",
                                "content": "C. 4种（纯电/混动/燃油/增程）",
                                "is_answer": 1,
                                "isChange": -1
                            }
                        ],
                        "correctItem": false
                    },
                    {
                        "id": "q3",
                        "type": 0, // 改为单选题
                        "title": "红旗H5 PHEV的纯电续航与馈电油耗是多少？",
                        "subtext": "纯电170km，综合1600km超级续航，进阶控场百公里3.75L最低荷电状态油耗长短途出行无忧。买混动到红旗",
                        "items": [
                            {
                                "id": "q3_a",
                                "content": "A. 纯电150km｜油耗4.5L/100km",
                                "is_answer": 0,
                                "isChange": -1
                            },
                            {
                                "id": "q3_b",
                                "content": "B. 纯电170km｜油耗3.75L/100km",
                                "is_answer": 1,
                                "isChange": -1
                            },
                            {
                                "id": "q3_c",
                                "content": "C. 纯电200km｜油耗4.0L/100km",
                                "is_answer": 0,
                                "isChange": -1
                            }
                        ],
                        "correctItem": false
                    }
                ]
            }]
        }

        if (res.code === 200) {
            let newAnsList = res.data[0]
            newAnsList.interlocution.forEach(j => {
                j.items.forEach(k => {
                    k.isChange = -1
                })
            })
            this._checkIsMutil(newAnsList.interlocution[this.data.index])

            this.setData({
                projectList: newAnsList,
                answerList: newAnsList.interlocution,
                isOptionLocked: false,
                showCorrectHint: false // 初始不显示正确提示
            })
        } else {
            wx.showToast({
                title: res.message,
                icon: "none"
            })
        }
    },

    handleRetry() {
        let currentIdx = this.data.index;
        let currentQues = this.data.answerList[currentIdx];
        currentQues.items.forEach(item => {
            item.isChange = -1;
        });
        currentQues.correctItem = false;

        // 清除计时器
        if (this.data.timer) {
            clearTimeout(this.data.timer);
            this.setData({
                timer: null
            });
        }

        this.setData({
            answerList: this.data.answerList,
            isError: false,
            showCorrectHint: false, // 隐藏正确提示
            MutilNum: true,
        });
    },

    // 选择题目逻辑
    onSelect(e) {
        const {
            changeidx,
            answer
        } = e.currentTarget.dataset;
        const currentQues = this.data.answerList[this.data.index];
        const currentItems = currentQues.items;
        let isCorrect = false;

        // 若选项已锁定（单选已选对），直接返回
        if (this.data.isOptionLocked && currentQues.type === 0) return;

        // 清除错误状态
        this.setData({
            isError: false,
            errorMsg: '',
            showCorrectHint: false // 重置正确提示状态
        });

        // 清除之前的计时器
        if (this.data.timer) {
            clearTimeout(this.data.timer);
            this.setData({
                timer: null
            });
        }

        // 单选逻辑
        if (currentQues.type === 0) {
            // 标记选择
            currentItems.forEach((item, idx) => {
                item.isChange = idx === changeidx - 1 ? 1 : -1;
            });
            // 校验答案
            if (currentItems[changeidx - 1].is_answer === 1) {
                isCorrect = true;
                this.setData({
                    isOptionLocked: true,
                    showCorrectHint: true // 显示正确提示
                });

                // 设置自动跳转计时器
                const timer = setTimeout(() => {
                    this.goToNext();
                }, 1500);
                this.setData({
                    timer
                });
            } else {
                // 答错
                currentItems[changeidx - 1].isChange = 0;
                this.setData({
                    isError: true,
                    errorMsg: currentQues.subtext
                });
                // 延迟重置选项，让用户有时间看到错误提示
                setTimeout(() => {
                    currentItems.forEach(item => {
                        item.isChange = -1; // 重置为未选择状态
                    });
                    this.setData({
                        answerList: this.data.answerList,
                    });

                }, 500); // 2秒后重置
            }
        }
        // 多选逻辑（已全部改为单选，此部分保留但不触发）
        else if (currentQues.type === 1) {
            // ...（保留原有逻辑但不会执行）
        }

        currentQues.correctItem = isCorrect;
        this.setData({
            answerList: this.data.answerList
        });
    },

    // 自动跳转下一题
    goToNext() {
        if (this.data.index !== 2) {
            num = (num + 1) % 3
            lineW = 33.3 * (num + 1)
            this._checkIsMutil(this.data.answerList[num])
            this.setData({
                index: num,
                line_width: lineW,
                MutilNum: true,
                isOptionLocked: false,
                isError: false,
                showCorrectHint: false // 重置正确提示状态
            })
        } else {
            // 全部完成
            const allCorrect = this.data.answerList.every(ques => ques.correctItem)
            if (allCorrect) {
                console.log('>>>>>>>>>>>>>>>>全部正确')
                // 原接口逻辑...
                this.signIn()
            } else {
                wx.showToast({
                    title: '答题有误，请重新检查',
                    icon: 'none'
                })
                this.data.answerList.forEach(ques => {
                    ques.items.forEach(item => item.isChange = -1)
                    ques.correctItem = false
                })
                this.setData({
                    answerList: this.data.answerList,
                    index: 0,
                    line_width: 33.3,
                    num: 0,
                    lineW: 33.3,
                    isOptionLocked: false,
                    showCorrectHint: false // 重置正确提示状态
                })
            }
        }
    },
    signIn() {
        var that = this
        console.log('>>>>>')
        reqJs.playGame(this.data.id).then(res => {
            console.log('>>>>>', res)
           if(res.code != 200){
               return
           }
           wx.showModal({
             title: '打卡成功',
             content: '',
             complete: (res) => {
               wx.redirectTo({
                 url: '/pages/index/index',
               })
             }
           })
            that.setData({
                itemFlag:true,
            })
            
            console.log(this.data)

        }).catch(error => {
            console.log(error)
        })
    },
    // 私有方法：判断是否为多选
    _checkIsMutil(ques) {
        const mutilCount = ques.items.reduce((sum, item) => sum + item.is_answer, 0)
        this.setData({
            isMutil: mutilCount > 1
        })
    },

    zhidao() {
        wx.navigateTo({
            url: '/pages/index/index'
        })
    },

    onShow() {
        this.getAnswerList()
        num = 0
        lineW = 33.3
    },

    onUnload() {
        // 清除计时器防止内存泄漏
        if (this.data.timer) {
            clearTimeout(this.data.timer);
        }
    },

    // 其他生命周期函数
    onReady() {},
    onHide() {},
    onPullDownRefresh() {},
    onReachBottom() {}
})